//
//  WBUserAccount.swift
//  仿写微博
//
//  Created by tuimao on 17/7/20.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit

fileprivate let accountFile:NSString = "uesraccount.json"
class WBUserAccount: NSObject {
    //用户令牌
    var access_token:String? //= "2.00h5f9LGYwAS7Da9016958c1OfGM4C"
    //用户代号
    var uid:String?
    //accessToken的生命周期
    var expires_in: TimeInterval = 0{ 
        didSet{
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //开发者使用日期或者测试账号的使用日期
    var expires_date:Date?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    
    //重写
    override var description: String{
        return yy_modelDescription()
    }
    //重写构造函数
    override init() {
        super.init()
        //从磁盘中读取保存的数据
        guard let filePath = accountFile.cz_appendDocumentDir(),
        //文件路径的二进制转换
            let data = NSData(contentsOfFile: filePath)else{
                return
        }
        //json序列化
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: [])
        //字典转模型
        yy_modelSet(withJSON: dict ?? [:])
        print(filePath)
        //判断账户是否过期
        if expires_date?.compare(Date.init(timeIntervalSinceNow: 0)) == .orderedAscending {
            //把账户信息设置为nil
            access_token = nil
            uid = nil
            //删除document中的过期文件
            _ = try? FileManager.default.removeItem(atPath: filePath)
            print("no")
        }
        print("ok")
    }
    
    
    //保存账户信息
    func saveAccount(){
        //模型转字典
        var dict = self.yy_modelToJSONObject() as? [String:AnyObject] ?? [:]
        //删除字典中不要的键
        dict.removeValue(forKey: "expires_in")
        //确保路径和data有值
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountFile.cz_appendDocumentDir() else{
                
                return
        }
        
        (data as NSData).write(toFile: filePath, atomically: true)
        print(filePath)
    }
    
    
}
